package com.tensquare.article.service;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.tensquare.article.client.NoticeClient;
import com.tensquare.article.dao.ArticleDao;
import com.tensquare.article.pojo.Article;
import com.tensquare.article.pojo.Notice;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import util.IdWorker;

import java.util.*;

@Service
public class ArticleService {
    @Autowired
    private ArticleDao articleDao;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private NoticeClient noticeClient;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;


    public List<Article> findAll() {
        return articleDao.selectList(null);
    }

    public Article findById(String articleId) {
        return articleDao.selectById(articleId);
    }

    public void save(Article article) {
        //TODO:使用jwt鉴权获取当前用的信息，用户id，也就是文章作者id
        String userId = "3";
        article.setUserid(userId);
        //使用分布式"id生成器
        String id = idWorker.nextId() + "";
        article.setId(id);

        //初始化数据
        article.setVisits(0);     //浏览量
        article.setThumbup(0);
        article.setComment(0);

        //新增
        articleDao.insert(article);

        //新增文章后，创建消息，通知给订阅者


        //获取订阅者信息
        String authorKey = "article_author_" +  userId;
        Set<String> set = redisTemplate.boundSetOps(authorKey).members();

        //给订阅者创建消息通知
        for (String uid : set) {
            //  创建消息对象
            Notice notice = new Notice();
            notice.setReceiverId(uid);

            notice.setOperatorId(userId);

            notice.setAction("publish");

            notice.setTargetType("article");

            notice.setTargetId(id);

            notice.setType("sys");

            noticeClient.save(notice);
        }
        rabbitTemplate.convertAndSend("article_subscribe",userId,id);
    }

    public void updateById(Article article) {
        // 根据主键id修改
        articleDao.updateById(article);

        /*// 根据条件修改
        // 创建条件对象
        EntityWrapper<Article> wrapper = new EntityWrapper<>();
        // 设置条件
        wrapper.eq("id",article.getId());
        articleDao.update(article,wrapper);*/
    }

    public void deleteById(String articleID) {
        articleDao.deleteById(articleID);
    }

    public Page<Article> findByPage(Map<String, Object> map, Integer page, Integer size) {
        // 设置查询条件
        EntityWrapper<Article> wrapper = new EntityWrapper<>();
        Set<String> keySet = map.keySet();
        for (String key : keySet) {
            /*if(map.get(key) != null){
                wrapper.eq(key,map.get(key));
            }*/
            wrapper.eq(map.get(key) != null,key,map.get(key));
        }
        //设置分页参数
        Page<Article> pageData = new Page<>(page,size);


        List<Article> list = articleDao.selectPage(pageData,wrapper);
        pageData.setRecords(list);

        //返回
        return pageData;
    }

    public Boolean subscribe(String articleId, String userId) {
        //根据文章id查询文章作者id
        String authorId = articleDao.selectById(articleId).getUserid();

        RabbitAdmin rabbitAdmin = new RabbitAdmin(rabbitTemplate.getConnectionFactory());

        DirectExchange exchange = new DirectExchange("article_subscribe");
        rabbitAdmin.declareExchange(exchange);

        Queue queue = new Queue("article_subscribe_" + userId, true);

        Binding binding = BindingBuilder.bind(queue).to(exchange).with(authorId);

        //存放用户订阅信息的集合，里面存放作者id
        String userKey = "article_subscribe_" + userId;
        //存放作者订阅这信息的集合，里面存放这订阅者id
        String authorKey = "article_author_" + authorId;
        //查询用户的订阅关系，是否有订阅作者
        Boolean flag = redisTemplate.boundSetOps(userKey).isMember(authorId);

        if(flag == true){
            //如果有订阅作者，取消订阅
            //在用户订阅信息的集合中，删除订阅的作者
            redisTemplate.boundSetOps(userKey).remove(authorId);
            //作者订阅信息的集合中，删除订阅者
            redisTemplate.boundSetOps(authorKey).remove(userId);

            rabbitAdmin.removeBinding(binding);
            //返回false
            return false;
        }else {
            //如果没有订阅作者，就进行订阅
            //在用户订阅信息中，添加订阅的作者
            redisTemplate.boundSetOps(userKey).add(authorId);
            //在作者订阅者信息中，添加订阅者
            redisTemplate.boundSetOps(authorKey).add(userId);

            rabbitAdmin.declareQueue(queue);
            rabbitAdmin.declareBinding(binding);
            return true;
        }

    }

    //文章点赞
    public void thumbup(String articleId, String userId) {
        Article article = articleDao.selectById(articleId);
        article.setThumbup(article.getThumbup() + 1);
        articleDao.updateById(article);

        //点赞成功后，需要发送消息给文章作者（点对点消息）
        Notice notice = new Notice();
        // 接收消息用户的ID
        notice.setReceiverId(article.getUserid());
        // 进行操作用户的ID
        notice.setOperatorId(userId);
        // 操作类型（评论，点赞等）
        notice.setAction("publish");
        // 被操作的对象，例如文章，评论等
        notice.setTargetType("article");
        // 被操作对象的id，例如文章的id，评论的id'
        notice.setTargetId(articleId);
        // 通知类型
        notice.setType("user");

        //保存消息
        noticeClient.save(notice);

        //1 创建Rabbit管理器
        RabbitAdmin rabbitAdmin = new RabbitAdmin(rabbitTemplate.getConnectionFactory());

        //2 创建队列，每个用户都有自己的队列，通过用户id进行区分
        Queue queue = new Queue("article_thumbup_" + article.getUserid(), true);
        rabbitAdmin.declareQueue(queue);

        //3 发送消息
        rabbitTemplate.convertAndSend("article_thumbup_"+article.getUserid(),articleId);
    }
}
